function debounce(fn, delay) {
  let timer;

  return function() {
    const context = this;
    const args = arguments;

    if (timer) {
      clearTimeout(timer);
    }

    timer = setTimeout(() => {
      timer = null;
      Promise.resolve(fn.apply(context, args)).then(() => {
        timer = null;
      });
    }, delay);
  }
}

function preventDoubleClick(handler, delay = 1000) {
  let timer;

  return function(event) {
    const context = this;
    const args = arguments;

    if (timer) {
      clearTimeout(timer);
    }

    timer = setTimeout(() => {
      timer = null;
      Promise.resolve(handler.call(context, event, ...args)).then(() => {
        timer = null;
      });
    }, delay);
  }
}

module.exports = {
  preventDoubleClick: preventDoubleClick,
};
